package union

import (
	"fmt"
	"gitee.com/golang-module/carbon"
	log2 "github.com/name5566/leaf/log"
	"server/game/bag"
	"server/game/item"
	"server/game/player"
	"server/util"
	"sync"
	"time"
)

type UnionLogic struct {
	dao   *UnionDao
	mutex sync.Mutex
}

func NewUnionLogic() *UnionLogic {
	return &UnionLogic{
		dao: NewUnionDao(),
	}
}
func (v *UnionLogic) GetVehicleInfo(unionId int32) (Union, error) {
	return v.dao.getUnionInfo(unionId)
}
func (v *UnionLogic) GetVehicleList(userId string) ([]Union, error) {
	return v.dao.getUnionList(userId)
}
func (v *UnionLogic) UpUserLevel(userId string, unionId int32, step int32) (Union, error) {
	unionInfo, err := v.dao.getUnionInfo(unionId)
	if err != nil {
		return unionInfo, fmt.Errorf("不要下请求s")
	}
	for key, userUnionInfo := range unionInfo.ReYuanList {
		if userUnionInfo.UserId == userId {
			unionInfo.ReYuanList[key].Level = unionInfo.ReYuanList[key].Level + int64(step)
		}
	}
	err = v.dao.upUserLevel(userId, unionId, unionInfo.ReYuanList)
	if err != nil {
		return unionInfo, fmt.Errorf("升级失败")
	}
	return unionInfo, nil

}
func (v *UnionLogic) UpUnionLevel(userId string, unionId int32, step int64) (Union, error) {
	unionInfo, err := v.dao.getUnionInfo(unionId)
	if err != nil {
		return unionInfo, fmt.Errorf("不要下请求s")
	}
	unionInfo.Level = unionInfo.Level + int32(step)
	err = v.dao.upUnionLevel(userId, unionId, unionInfo.Level)
	if err != nil {
		log2.Error("升级失败，信息是%s", err.Error())
		return unionInfo, err
	}
	return unionInfo, nil
}
func (v *UnionLogic) ShopInfo(userId string) (UnionShop, error) {
	return v.dao.getUnionShop(userId)
}
func (v *UnionLogic) JoinUnion(userId string, unionId int32) (Union, error) {
	unionInfo, err := v.dao.getUnionInfoByUnionId(unionId)

	if err != nil {
		return unionInfo, fmt.Errorf("不要下请求s")
	}
	for _, uinfo := range unionInfo.ReYuanList {
		if uinfo.UserId == userId {
			return unionInfo, fmt.Errorf("已经加入了该工会")
		}

	}
	userUnionInfo := &UnionUserInfo{
		UnionId:    unionId,
		UserId:     userId,
		UserLevel:  1,
		QingAnList: make([]QianAnInfo, 0),
	}
	unionInfo.ReYuanList = append(unionInfo.ReYuanList, *userUnionInfo)
	err = v.dao.joinUnion(unionId, unionInfo.ReYuanList)
	v.InitUserShop(userId)
	v.InitUserBuild(userId)
	if err != nil {
		return unionInfo, err
	}
	err = player.EnJoinUnion(userId, unionId)
	if err != nil {
		return unionInfo, fmt.Errorf("更新用户失败")
	}
	return unionInfo, nil
}
func (v *UnionLogic) NewUnion(userId string) (Union, error) {
	unionId, err := util.IdGen()
	newUnionInfo := Union{
		Master:     userId,
		UnionId:    int32(unionId),
		CreateTime: time.Now().Unix(),
		ReYuanList: make([]UnionUserInfo, 0),
		Level:      1,
	}
	err = v.dao.insert(userId, newUnionInfo)
	if err != nil {
		return newUnionInfo, err
	}
	_, err = v.JoinUnion(userId, int32(unionId))
	if err != nil {
		return newUnionInfo, err
	}
	return newUnionInfo, nil
}
func (v *UnionLogic) BaiFang(userId string, unionId int32, npcId int32) (Union, error) {
	unionInfo, err := v.dao.getUnionInfo(unionId)
	if err != nil {
		return unionInfo, fmt.Errorf("不要下请求s")
	}
	for key, reYuan := range unionInfo.ReYuanList {
		if reYuan.UserId == userId {
			if len(reYuan.QingAnList) == 0 {
				unionInfo.ReYuanList[key].QingAnList = append(unionInfo.ReYuanList[key].QingAnList,
					QianAnInfo{
						CreateTime: time.Now().Unix(),
						NpcId:      npcId,
					})
			} else {
				for qingAnKey, qingAnInfo := range reYuan.QingAnList {
					if util.IsSameDay(qingAnInfo.CreateTime) && qingAnInfo.NpcId == npcId {
						return unionInfo, fmt.Errorf("已经拜访过了，不能拜访")
					} else if !util.IsSameDay(qingAnInfo.CreateTime) && qingAnInfo.NpcId == npcId {
						unionInfo.ReYuanList[key].QingAnList[qingAnKey].CreateTime = time.Now().Unix()
					} else {
						unionInfo.ReYuanList[key].QingAnList = append(unionInfo.ReYuanList[key].QingAnList,
							QianAnInfo{
								CreateTime: time.Now().Unix(),
								NpcId:      npcId,
							})

					}
				}
			}

		}
	}
	log2.Debug("%v", unionInfo.ReYuanList)
	err = v.dao.baiFang(unionId, unionInfo.ReYuanList)
	if err != nil {
		log2.Error("更新失败 错误信息是%s", err.Error())
		return unionInfo, err
	}
	return unionInfo, nil
}
func (v *UnionLogic) InitUserShop(uid string) {
	for i := 0; i < 12; i++ {
		var shop = UnionShop{UserId: uid, LingQuTimes: 999999, ItemId: i}
		v.dao.insertShop(uid, shop)
	}
}
func (v *UnionLogic) Build(uid string, bType int) (map[string]interface{}, error) {
	info, err := v.dao.BuildInfo(uid, bType)
	if err != nil {
		return nil, err
	}
	if info.CDTime > time.Now().Unix() {
		return nil, fmt.Errorf("cd时间没到")
	}
	switch bType {
	case 1:
		info.Times += 1
		info.CDTime = carbon.Now().AddMinutes(10).Timestamp()
	case 2:
		_, err = bag.EnUseItem(uid, item.Zuanshi, 50)
		info.Times += 1
		info.CDTime = carbon.Tomorrow().Timestamp()
		break
	case 3:
		info.Times += 1
		_, err = bag.EnUseItem(uid, item.Zuanshi, 200)
		info.CDTime = carbon.Tomorrow().Timestamp()
		break
	}
	if err != nil {
		return nil, err
	}
	bagList, _ := bag.EnGetUserItem(uid)
	playerInfo, _ := player.EnGetUserInfo(uid)
	uInfo, _ := v.dao.getUnionInfo(playerInfo.UnionId)
	lock := NewUnionLock("union")
	lock.lockKey(string(playerInfo.UnionId))
	uInfo.BuildDu = uInfo.BuildDu + 1
	err = v.dao.upBuildValue(uInfo.UnionId, uInfo.BuildDu)
	err = v.dao.Build(uid, bType, info.Times, info.CDTime)
	lock.unlockKey(string(playerInfo.UnionId))
	if err != nil {
		return nil, err
	}
	var ret = make(map[string]interface{}, 0)
	ret["union_build"] = info
	ret["bag_list"] = bagList
	return ret, nil
}
func (v *UnionLogic) InitUserBuild(userId string) {
	for i := 1; i <= 4; i++ {
		data := BuildUnion{
			UserId:    userId,
			BuildType: i,
			Times:     0,
			CDTime:    time.Now().Unix(),
		}
		v.dao.insertUnionBuild(userId, data)
	}
}
func (v *UnionLogic) BuildList(userId string) ([]BuildUnion, error) {
	return v.dao.BuildList(userId)
}
